package model

import (
	"gorm.io/gorm/clause"
	"server/common"
	"server/pkg/app"
)

type Article struct {
	Model
	Name         string `gorm:"column:name;not null;type:varchar(100)" json:"title"`
	Views        int    `gorm:"column:views;not null;type:int" json:"views"`
	LikeCount    int    `gorm:"column:likecount;not null;type:int" json:"like_count"`
	CommentCount int    `gorm:"column:commentcount;not null;type:int" json:"comment_count"`
	Content      string `gorm:"column:content;not null;type:longtext" json:"content"`

	OwnerID int   `json:"owner_id"`
	Owner   Owner `gorm:"references:ID"`
}

func (a *Article) TableName() string {
	return "article"
}

func (ar *Article) Info() error {
	if err := common.DB.Omit(clause.Associations).Where("name = ?", ar.Name).Find(&ar); err != nil {
		return err.Error
	}
	return nil
}

func (ar *Article) List(page *app.Page) ([]Article, int64) {
	ar_list := []Article{}
	var count int64
	if err := common.DB.Debug().Preload(clause.Associations).Order("id desc").Limit(page.Size).Offset((page.Page - 1) * page.Size).Find(&ar_list).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return ar_list, count
	}
	return ar_list, count
}

func (ar *Article) Create() error {
	if err := common.DB.Omit(clause.Associations).Create(&ar).Error; err != nil {
		return err
	}
	return nil
}

func (ar *Article) Update() error {
	if err := common.DB.Omit(clause.Associations).Where("name = ?", ar.Name).Updates(&ar).Error; err != nil {
		return err
	}
	return nil
}

func (ar *Article) Delete() error {
	if err := common.DB.Where("name = ?", ar.Name).Delete(&ar).Error; err != nil {
		return err
	}
	return nil
}
